/**
 * Created by Administrator on 2016/11/12.
 */
var config = require('config.js');
var app = {
  /**
   *   存储值
   */
  setData: function(key, value) {
    // if (!value) {
    //   return;
    // }
    if (typeof value == 'object') {
      return wx.setStorageSync(key, JSON.stringify(value));
    } else {
      return wx.setStorageSync(key, value);
    }
  },
  /**
   * 获取存储的值
   * @key 需要的值对应的Key
   * @defaultData 当返回的值是空的时候，返回
   */
  getData(key, defaultData) {
    try {
      var re = wx.getStorageSync(key);
      if (re) {
        e.detail
        return JSON.parse(re);
      } else {
        return defaultData;
      }
    } catch (e) {
      return re;
    }
  },

  removeData(data) {
    wx.removeStorageSync(data);
  },

  setToken: function(token) { //存储Token值
    return wx.setStorageSync("token", token); //将 data 存储在本地缓存中指定的 key 中，会覆盖掉原来该 key 对应的内容，这是一个同步接口。
  },
  getToken: function() { //获取token值
    return wx.getStorageSync("token"); //从本地缓存中同步获取指定 key 对应的内容。　
  },

  removeToken: function() { //删除token值
    wx.removeStorageSync("token"); //从本地缓存中同步移除指定 key 。
  },


  doPost: function(url, data, succCallBack, errorCallBack) {
    app.requestData(url, data, "POST", succCallBack, errorCallBack);
  },

  doGet: function(url, data, succCallBack, errorCallBack) {
    var reqParam = "";
    for (var key in data) {
      reqParam += key + "=" + data[key] + "&"
    }
    reqParam = reqParam.substr(0, reqParam.length - 1);
    app.requestData(url + "?" + reqParam, {}, "GET", succCallBack, errorCallBack);
  },

  requestData: function(url, data, method, succCallBack, errorCallBack) {
    const token = app.getToken();
    let a;
    if (method == 'GET') {
      a = '';
    } else if (method == 'POST') {
      a = config.ServerUrl;
    }
    wx.request({
      url: a + url,
      data: data,
      method: method, // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
      header: {
        'content-type': 'application/x-www-form-urlencoded',
        'auth': token
      }, // 设置请求的 header
      success: function(res) {
        succCallBack(res.data);
      },
      fail: function(res) {
        wx.showToast({
          title: '网络错误，发送请求失败',
          icon: 'none',
          duration: 2000
        })
      },
      complete: function(res) {
        console.log(res);
      }
    })
  },

  /**
   * 微信支付
   * order_id 支付的订单
   * form_id 
   */
  pay: (order_id, form_id) => {
    return new Promise((resolve, reject) => {
      app.doPost('/wechatPay/wechatSign', {
        order_id,
        form_id
      }, (res) => {
        if (res.code === 1) {
          const timeStamp = new Date().getTime() + "";
          const options = res.data;
          options.success = (res) => {
            console.log("AddFormId：", res);
            resolve();
          };
          options.fail = (res) => {
            console.log("取消支付" + res);
            reject(res.errMsg);
            // wx.showToast({
            //     image: '../image/icon/error.png',
            //     title: "支付失败：" + res.errMsg,
            // });
          };
          console.log(options);
          wx.requestPayment(options);
        } else {
          wx.showToast({
            title: res.msg,
          })
          console.log(res.msg);
          reject(res.msg);
        }
      });
    });
  },

  /**
   * 获取access_token
   */
  getaccess_token: (data) => {
    return new Promise((resolve, reject) => {
      wx.getUserInfo({
        success: (info) => {
          wx.request({
            url: `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${config.appid}&secret=${config.appsecret}`,
            success: (result) => {
              let params = {
                access_token: result.data.access_token,
                touser: info.userInfo
              };
              wx.request({
                url: 'https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send',
                data: params,
                method: 'POST',
                success: (res) => {
                  console.log(res);
                },
                fail: (res) => {

                }
              })
              resolve(res.data);
            },
            fail: (res) => {
              // console.log(res);
            }
          });
        },
        fail: (res) => {
          //console.log(res);
          reject();
        }
      })
    })
  },
  /**
   * 获取OpenID
   */
  getOpenId: function() {
    return new Promise((resolve, reject) => {
      const that = this;
      wx.login({
        success: function(res) {
          app.doPost("/wechatPay/xcxGetOpenId", {
            code: res.code
          }, (result) => {
            if (result.code == 1) {
              resolve(result.data.openid);
            } else {
              reject(result.msg);
            }
          });
        },
        fail: function(err) {
          //   console.log(err);
        }
      });
    });
  },

  /**
   * 验证手机号
   */
  checkPhone: function(phone) {
    const phoneReg = /^[1][3,4,5,7,8][0-9]{9}$/;
    if (!phoneReg.test(phone)) {
      return false;
    } else {
      return true;
    }
  }

}
module.exports = app;